# -*- encoding:utf-8 -*-
# @time: 2023/3/15 15:36
# @author: Maxs_hu
from django.http import JsonResponse
from django.shortcuts import redirect
from django.shortcuts import render
from django_redis import get_redis_connection

from utils.encrypt import md5
from utils.response import baseResponse
from utils.send_msg import send_sms
from web import models
from web.forms.account import FM
from web.forms.account import smsForm
from web.forms.account import verifyForm


# # 已经在中间件中验证了用户登录. 所以不需要设置装饰器了
# def auth(func):
#     def inner(request, *args, **kwargs):
#         # 判断用户session是否存在
#         if not request.session.get('user_info'):
#             return redirect('/login.html')
#         res = func(request, *args, **kwargs)
#         return res
#
#     return inner


def login(request):
    if request.method == 'GET':
        obj = FM()
        return render(request, 'login.html', {'obj': obj})

    obj = FM(request.POST)
    # 1. 接收并获取数据
    if not obj.is_valid():
        return render(request, 'login.html', {'obj': obj})
    data = obj.cleaned_data
    role = data['role']
    username = data['username']
    password = data['password']

    # 2. 取数据库校验
    mapping = {'1': 'ADMIN', '2': 'CUSTOMER'}
    if role not in mapping:
        return render(request, 'login.html', {'error': '角色不存在', 'obj': obj})

    if role == '1':
        # 对密码加密后去数据库进行校验
        user_object = models.Administrator.objects.filter(active=1, username=username, password=md5(password)).first()
    else:
        user_object = models.Customer.objects.filter(active=1, username=username, password=md5(password)).first()

    # 3. 校验失败
    if not user_object:
        return render(request, 'login.html', {'error': '用户名或密码错误', 'obj': obj})

    # 4. 校验成功
    # 保存用户session
    request.session['user_info'] = {'role': mapping[role], 'username': username, 'id': user_object.id}
    # request.session.set_expiry(10)  # 默认为两周

    return redirect('/home.html')


def sms_login(request):
    if request.method == "GET":
        obj = smsForm()
        return render(request, 'sms_login.html', {'obj': obj})
    # 每一个请求都重复做校验
    # 1.校验电话号码合法性
    res = baseResponse()
    obj = smsForm(request.POST)
    if not obj.is_valid():
        res.status = False
        res.detail = obj.errors
        return JsonResponse(res.dict, json_dumps_params={"ensure_ascii": False})

    # 2.校验电话号码是否存在
    role = request.POST.get('role')
    mobile = request.POST.get('mobile')
    if role == '1':
        # 因为后面需要用户信息. 所以这里不能用exist()
        user_obj = models.Administrator.objects.filter(active=1, mobile=mobile).first()
    else:
        user_obj = models.Customer.objects.filter(active=1, mobile=mobile).first()
    if not user_obj:
        res.status = False
        res.detail = {'mobile': ['手机号不存在']}
        return JsonResponse(res.dict, json_dumps_params={"ensure_ascii": False})

    # 3.校验验证码是否正确
    code = request.POST.get('code')
    conn = get_redis_connection("default")  # 到settings中找到default中的redis配置
    cache_code = conn.get(mobile)
    if not cache_code:
        res.status = False
        res.detail = {'code': ['验证码不存在或失效']}
        return JsonResponse(res.dict, json_dumps_params={"ensure_ascii": False})
    if not cache_code.decode('utf-8') == code:  # 这里要注意从redis中查出的code是bytes
        res.status = False
        res.detail = {'code': ['验证码错误']}
        return JsonResponse(res.dict, json_dumps_params={"ensure_ascii": False})

    # 4.存入用户登录信息
    mapping = {'1': 'ADMIN', '2': 'CUSTOMER'}
    request.session['user_info'] = {'role': mapping[role], 'username': user_obj.username, 'id': user_obj.id}
    # request.session.set_expiry(10)  # 默认为两周
    res.status = True
    return JsonResponse(res.dict, json_dumps_params={'ensure_ascii': False})


def sms_send(request):
    res = baseResponse()

    # 1.验证电话号码合法性
    obj = verifyForm(request.POST)
    if not obj.is_valid():
        res.status = False
        res.detail = obj.errors  # ErrorDict
        return JsonResponse(res.dict, json_dumps_params={"ensure_ascii": False})  # 可显示中文

    # 2.判断电话号码是否存在
    role = request.POST.get('role')
    mobile = request.POST.get('mobile')
    if role == '1':
        user_obj = models.Administrator.objects.filter(active=1, mobile=mobile).exists()
    else:
        user_obj = models.Customer.objects.filter(active=1, mobile=mobile).exists()
    if not user_obj:
        res.status = False
        res.detail = {'mobile': ['手机号不存在']}
        return JsonResponse(res.dict, json_dumps_params={'ensure_ascii': False})

    # 3.发送验证码
    mobile = request.POST.get('mobile')
    sms, info = send_sms(mobile)
    if info != "Ok":
        res.status = False
        res.detail = {'code': ['短信发送失败']}
        return JsonResponse(res.dict, json_dumps_params={'ensure_ascii': False})

    # 4.将验证码存入django-redis缓存中
    conn = get_redis_connection("default")  # 到settings中找到default中的redis配置
    conn.set(mobile, sms, ex=180)  # 设置失效时间

    return JsonResponse(res.dict, json_dumps_params={'ensure_ascii': False})


def home(request):
    username = request.user_obj.username
    return render(request, 'home.html', {'username': username})


def user(request):
    return render(request, 'user.html')


def logout(request):
    request.session.clear()  # 清除session
    return redirect('/login.html')
